package com.zhsm.fuxi.mvp.ui.activitys

import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.CheckBox
import com.hankkin.reading.base.BaseMvpActivity
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.zhsm.fuxi.R
import com.zhsm.fuxi.bean.OrderInfo
import com.zhsm.fuxi.bean.OrderListResp
import com.zhsm.fuxi.mvp.contract.InvoiceContract
import com.zhsm.fuxi.mvp.presenter.InvoicePresenter
import com.zhsm.fuxi.mvp.ui.adapter.InvoiceRecyclerAdapter
import com.zhsm.paipaiout.baselibrary.widget.view.PageLayout
import kotlinx.android.synthetic.main.activity_invoice.*
import kotlinx.android.synthetic.main.layout_head_bar.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick

/**
 * Created by GuZhC on 2018/11/19.
 * describe:
 */
class InvoiceActivity : BaseMvpActivity<InvoicePresenter>(), InvoiceContract.IView,
        PageLayout.OnRetryClickListener, OnRefreshLoadMoreListener {

    var pager = 1
    var ids: StringBuilder = StringBuilder()
    val mAdapter: InvoiceRecyclerAdapter = InvoiceRecyclerAdapter(ArrayList<OrderInfo>())
    val mPageLayout by lazy {
        PageLayout.Builder(this)
                .initPage(findViewById(R.id.invoiceRecycler))
                .setDefaultEmptyText("暂无可开发票订单")
                .setEmptyDrawable(R.mipmap.empty_order)
                .setDefaultErrorText("网络错误，请点击刷新")
                .setErrorDrawable(R.mipmap.error_net)
                .setOnRetryListener(this)
                .create()
    }


    override fun getLayoutId(): Int {
        return R.layout.activity_invoice
    }

    override fun registerPresenter() = InvoicePresenter::class.java

    override fun initView() {
        setMiuiStatusBar()
        setToolBar()
        invoiceRecycler.layoutManager = LinearLayoutManager(this)
        invoiceRecycler.adapter = mAdapter
        invoiceRefresh.setOnRefreshLoadMoreListener(this)
        mAdapter.setOnItemClickListener { _, _, position ->
            mAdapter.data[position].checked = !mAdapter.data[position].checked!!
            setBottom()
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            if (view.id == R.id.invoiceCb) mAdapter.data[position].checked = findViewById<CheckBox>(R.id.invoiceCb).isChecked
            setBottom()
        }

        invoiceNext.onClick {
            val intent = Intent(this@InvoiceActivity, InvoiceGiveActivity::class.java)
            intent.putExtra("orders", ids.toString())
            startActivity(intent)
//            LogUtils.e( "ids",ids.toString())
        }
        invoiceCbAll.onClick { _ ->
            if (mAdapter.data.isNotEmpty()) {
                mAdapter.data.forEachIndexed { index, orderInfo ->
                    mAdapter.data[index].checked = invoiceCbAll.isChecked
                }
                setBottom()
            }
        }
    }

    private fun setBottom() {
        mAdapter.notifyDataSetChanged()
        if (ids.isNotEmpty()) ids.delete(0, ids.length)
        var checkedNum = 0
        var checkedMoney = 0.00
        if (mAdapter.data.isNotEmpty()) {
            mAdapter.data.forEachIndexed { index, orderInfo ->
                if (orderInfo.checked!!) {
                    ids.append("${orderInfo.id},")
                    checkedNum++
                    orderInfo.amount?.let {
                        checkedMoney += it
                    }
                } else invoiceCbAll.isChecked = false
            }
            if (ids.isNotEmpty()) ids.deleteCharAt(ids.length - 1)
            invoiceNext.isEnabled = checkedNum > 0
            invoiceNum.text = checkedNum.toString()
            invoiceMoney.text = checkedMoney.toString()
        }
    }

    private fun setToolBar() {
        orderInvoiceHeadBar.imgLift.onClick { finish() }
        orderInvoiceHeadBar.tvTitle.text = "发票"
        orderInvoiceHeadBar.textRight.text = "开票历史"
        orderInvoiceHeadBar.textRight.visibility = View.VISIBLE
        orderInvoiceHeadBar.onClick { startActivity(Intent(this@InvoiceActivity, InvoiceHistoryActivity::class.java)) }
    }

    override fun onResume() {
        super.onResume()
        invoiceRefresh.autoRefresh()

    }
    override fun onRetry() {
        invoiceRefresh.autoRefresh()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout?) {
        if (haveMore)
            getPresenter().getInvoiceList(pager)
        else invoiceRefresh.finishLoadMoreWithNoMoreData()
    }

    override fun onRefresh(refreshLayout: RefreshLayout?) {
        pager = 1
        haveMore = true
        invoiceRefresh.isEnableLoadMore = true
        invoiceRefresh.setNoMoreData(false)
        getPresenter().getInvoiceList(pager)
    }

    var haveMore = true
    override fun getInvoiceListSucess(it: OrderListResp?) {
        if (it == null) getInvoiceistFail()
        it?.run {
            if (list!!.isNotEmpty()) {
                if (pager == 1) {
                    mAdapter.replaceData(list)
                    invoiceRefresh.finishRefresh(0, true)
                } else {
                    mAdapter!!.addData(list)
                    invoiceRefresh.finishLoadMore(0, true, false)
                }
                if (list?.size == pageSize) pager++
                else haveMore = false
                setBottom()
            } else{
                invoiceRefresh.finishRefresh(0, true)
                invoiceRefresh.finishLoadMore(0, true, false)
                haveMore = false
            }
            if (mAdapter.data.isEmpty()) {
                invoiceBottom.visibility = View.GONE
                mPageLayout.showEmpty()
                invoiceRefresh.isEnableLoadMore = false
            } else {
                mPageLayout.hide()
                invoiceBottom.visibility = View.VISIBLE
            }
        }
    }

    override fun getInvoiceistFail() {
        invoiceRefresh.finishRefresh(0, false)
        invoiceRefresh.finishLoadMore(0, false, false)
        mPageLayout.showError()
        invoiceBottom.visibility = View.GONE
        invoiceRefresh.isEnableLoadMore = false
    }


}